package com.xtayfjpk.zookeeper.test.master_workers.callback.master;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.data.Stat;

import com.xtayfjpk.zookeeper.test.master_workers.Master;
import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseDataCallback;

public class TaskDataCallback extends BaseDataCallback {
	private static final Logger LOGGER = Logger.getLogger(TaskDataCallback.class);
	private Master master;
	
	public TaskDataCallback(Master master) {
		this.master = master;
	}

	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx,
			byte[] data, Stat stat) {
		master.getTaskData((String)ctx);
	}
	
	@Override
	protected void okCaseAction(int rc, String path, Object ctx, byte[] data, Stat stat) {
		List<String> list = master.getWorkersCache().getChildren();
		//随机获取一个worker
		String designedWorker = list.get(master.getRandom().nextInt(list.size()));
		/*
         * Assign task to randomly chosen worker.
         */
		String assignmentPath = "/assign/" + 
				designedWorker + 
				"/" + 
				(String) ctx;
		LOGGER.info( "Assignment path: " + assignmentPath );
		//将待执行任务分配给指定worker
		master.createAssignment(assignmentPath, data);
	}
	
	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx,
			byte[] data, Stat stat) {
		LOGGER.error("Error when trying to get task data.", 
                KeeperException.create(Code.get(rc), path));
	}
}
